package com.naire.modul.template.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.common.dao.GeneralDaoImpl;
import net.common.service.PageBean;
import net.common.util.BeanUtils;

import com.naire.modul.project.pojo.Project;
import com.naire.modul.template.dao.TemplateDao;
import com.naire.modul.template.pojo.Template;
import com.naire.modul.template.vo.TemplateVo;

public class TemplateDaoImpl extends GeneralDaoImpl implements TemplateDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<TemplateVo> search(PageBean pageBean) throws Exception {
		StringBuilder hql = new StringBuilder("from Template where flag=0");
		List<TemplateVo> d = new ArrayList<TemplateVo>();
		List<Template> l = hibernateHandler.query(hql, pageBean);
		for (Template bean : l) {
			TemplateVo dv = new TemplateVo();
			BeanUtils.copyProperties(bean, dv);
			d.add(dv);
		}
		return d;
	}

	@Override
	public void insert(TemplateVo bean) throws Exception {
		Project p = (Project) hibernateHandler.find(Project.class, bean.getProject_id());
		Template pojo = new Template();
		BeanUtils.copyProperties(bean, pojo);
		pojo.setProject(p);
		hibernateHandler.insert(pojo);
	}

	@Override
	public void update(TemplateVo bean) throws Exception {
		Template pojo = (Template) hibernateHandler.find(Template.class,
				bean.getTemplate_id());
		BeanUtils.copyProperties(bean, pojo);
		hibernateHandler.update(pojo);
	}

	@Override
	public void updateFlag(TemplateVo bean) throws Exception {
		update(bean);
	}

	@SuppressWarnings("unchecked")
	@Override
	public TemplateVo find(Integer id) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("project_id", id);
		StringBuilder hql = new StringBuilder(
				"from Template where project.project_id=:project_id");
		List<Template> l = hibernateHandler.query(hql, params);
		if (l != null && l.size() > 0) {
			TemplateVo bean = new TemplateVo();
			BeanUtils.copyProperties(l.get(0), bean);
			return bean;
		} else {
			return null;
		}
	}
}
